﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.SessionState;
using System.IO;
using System.Text;

namespace PreguntaAlExperto
{
    public class DocumentHandler
        : IHttpHandler, IRequiresSessionState
    {
        private const string HOLDER_ASPX = "~/showDocument.aspx";

        public DocumentHandler()
        {
            // Nothing to do here.
        }

        public void ProcessRequest(System.Web.HttpContext context)
        {
            StreamReader sr;
            StringWriter sw = new StringWriter();
            StringBuilder merger = new StringBuilder();

            string documentPath = 
                ConfigurationManager.AppSettings["DocumentRepository"] +
                Path.GetFileNameWithoutExtension(context.Request.FilePath) + 
                ".html";

            try
            {
                context.Server.Execute(HOLDER_ASPX, sw);
                merger.Append(sw.ToString());

                sr = new StreamReader(documentPath, Encoding.UTF7);

                merger.Replace("<contextreplace></contextreplace>", sr.ReadToEnd());
            }
            catch (Exception e)
            {
                context.Response.Write(e);
            }
            finally
            {
                context.Response.Write(merger.ToString());
                context.Application.Lock();
            }

        }


        #region IHttpHandler Members

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }

        #endregion
    }
}
